package com.streamkar.rest;

import com.streamkar.constant.Constants;
import com.streamkar.constant.ReturnCode;
import com.streamkar.entity.base.Response;
import com.streamkar.entity.base.ResponseData;
import com.streamkar.entity.domain.Account;
import com.streamkar.entity.domain.Agency;
import com.streamkar.entity.domain.Talent;
import com.streamkar.entity.request.LoginRequest;
import com.streamkar.service.AccountService;
import com.streamkar.service.AgencyService;
import com.streamkar.service.TalentService;
import com.streamkar.util.AccountLocalCache;
import com.streamkar.util.Cryptos;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @ClassName AccountRest
 * @Description
 * @Author tyfrost
 * @Date 2018/11/13 下午11:50
 * @Version 1.0
 */
@RestController
public class AccountRest {

    private static final Logger LOGGER = LoggerFactory.getLogger(AccountRest.class);

    @Autowired
    AccountService accountService;

    @Autowired
    Environment environment;

    @Autowired
    AgencyService agencyService;

    @Autowired
    TalentService talentService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Response login(@RequestBody @Valid LoginRequest loginRequest, HttpServletRequest request, HttpServletResponse response) {
        ResponseData<Account> responseData = new ResponseData<>();
        String loginUrl = "";
        String role = "";
        switch (loginRequest.getUserType()) {
            case 1:
                loginUrl = environment.getProperty("agencies.url");
                role = Constants.AGENCY;
                break;
            case 2:
                loginUrl = environment.getProperty("monitors.url");
                role = Constants.MONITOR;
                break;
            case 3:
                loginUrl = environment.getProperty("managers.url");
                role = Constants.MANAGER;
                break;
            case 4:
                loginUrl = environment.getProperty("talentmanagers.url");
                role = Constants.TALENT_MANAGER;
                break;
            case 5:
                loginUrl = environment.getProperty("talents.url");
                role = Constants.TALENT;
                break;
            default:
                loginUrl = environment.getProperty("talentmanagers.url");
                role = Constants.TALENT_MANAGER;
                break;
        }
        // TODO
        Integer userId = null;
        if (5 == loginRequest.getUserType()) {
            userId = NumberUtils.toInt(loginRequest.getAccount());
        } else {
            userId = accountService.login(loginRequest.getAccount(), loginRequest.getPasswd(), loginUrl);
        }
        if (null != userId) {
            // 如果是代理 查询代理信息
            Account account = new Account();
            account.setUserId(userId);
            account.setRole(role);
            if (Objects.equals(1, loginRequest.getUserType())) {
                // 查询代理信息
                Agency agency = agencyService.agencyInfo(userId);
                account.setAccountInfo(agency);
            } else if (Objects.equals(5, loginRequest.getUserType())) {
                // 查询主播信息
                Talent talent = talentService.talentInfo(userId);
                account.setAccountInfo(talent);
            }
            AccountLocalCache.putCache(account.getUserId(), account);
            String sessionToken = Cryptos.aesEncrypt(String.valueOf(userId), Constants.TOKEN_KEY);
            Cookie sessionCookie = new Cookie(Constants.COOKIE_KEY, sessionToken);
            sessionCookie.setMaxAge(-1);
            sessionCookie.setPath("/");
            sessionCookie.setDomain(request.getRemoteHost());
            LOGGER.info("SessionToken is {}, the sessionCookie is {}...", sessionToken, sessionCookie.getDomain());
            response.addCookie(sessionCookie);
            response.setHeader(Constants.USER_TOKEN, sessionToken);
            responseData.setData(account);
        } else {
            responseData.setCode(ReturnCode.FAIL);
        }
        return responseData;
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    @ResponseBody
    public Response logout(HttpServletRequest request) {
        Response response = new Response();
        HttpSession session = request.getSession(false);
        if (null != session) {
            session.invalidate();
        }
        return response;
    }

    @RequestMapping("/check")
    public Response check(HttpServletRequest request) {
        ResponseData<Object> responseData = new ResponseData<>();
        HttpSession session = request.getSession(false);
        if (null != session && null != session.getAttribute(Constants.SESSION_KEY)) {
            responseData.setData(session.getAttribute(Constants.SESSION_KEY));
        } else {
            responseData.setData(null);
        }
        return responseData;
    }
}
